package cn.kwq.pcsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.kwq.pcsystem.common.Result;
import cn.kwq.pcsystem.common.ResultCode;
import cn.kwq.pcsystem.concurrent.ConcurrentJobThreadUtils;
import cn.kwq.pcsystem.concurrent.JobThreadConfig;
import cn.kwq.pcsystem.dto.RegisterDTO;
import cn.kwq.pcsystem.dto.SquadExcelDTO;
import cn.kwq.pcsystem.entity.DepartmentDic;
import cn.kwq.pcsystem.entity.MajorDic;
import cn.kwq.pcsystem.excel.SquadListener;
import cn.kwq.pcsystem.exception.CaptchaException;
import cn.kwq.pcsystem.exception.UserExistException;
import cn.kwq.pcsystem.exception.UserFormatException;
import cn.kwq.pcsystem.repository.SquadDicRepository;
import cn.kwq.pcsystem.service.DepartmentDicService;
import cn.kwq.pcsystem.service.MajorDicService;
import cn.kwq.pcsystem.utils.ExcelUtils;
import cn.kwq.pcsystem.vo.DepartmentDicVO;
import cn.kwq.pcsystem.vo.MajorDicVO;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kwq
 * @since 2023-03-12
 */
@RestController
@RequestMapping("/Dic")
public class DicController {

    @Autowired
    DepartmentDicService departmentDicService;
    @Autowired
    MajorDicService majorDicService;
    @Autowired
    SquadDicRepository squadDicRepository;

    @SaIgnore//可以匿名访问该接口
    @PostMapping("/findDepartmentDic")
    public Result findDepartmentDic(@RequestBody Map<String,String> obj) {
        String departmentName = obj.get("departmentName");
        QueryWrapper<DepartmentDic> wrapper=new QueryWrapper<>();
        wrapper.like("department_name",departmentName);
        List<DepartmentDic> list = departmentDicService.list(wrapper);
        return Result.success().data(list);
    }

    @SaIgnore//可以匿名访问该接口
    @PostMapping("/findMajorDic")
    public Result findMajorDic(@RequestBody Map<String,String> obj){
        String departmentName = obj.get("majorName");
        QueryWrapper<MajorDic> wrapper=new QueryWrapper<>();
        wrapper.like("major_name",departmentName);
        List<MajorDic> list = majorDicService.list(wrapper);
        return Result.success().data(list);
    }

    @SaIgnore//可以匿名访问该接口
    @GetMapping("/downloadDepartmentDicExcel")
    public Result downloadDepartmentDicExcel(HttpServletResponse response) throws IOException {
        List<DepartmentDic> list = departmentDicService.list();
        List<DepartmentDicVO> departmentDicVOList = list.stream().map(item -> {
            return DepartmentDicVO
                    .builder()
                    .num(Math.toIntExact(item.getDepartmentId()))
                    .departmentId(item.getDepartmentId())
                    .departmentName(item.getDepartmentName())
                    .remark(item.getRemark())
                    .build();
        }).toList();
        boolean success = ExcelUtils
                .writeExcel(DepartmentDicVO.class, departmentDicVOList, "部门代号", response, "校部门/学院代号");

        if (success){
            return Result.success();
        }
        return Result.error();
    }

    @SaIgnore//可以匿名访问该接口
    @GetMapping("/downloadMajorDicExcel")
    public Result downloadMajorDicExcel(HttpServletResponse response) throws IOException {
        List<MajorDic> list = majorDicService.list();
        List<MajorDicVO> listVO=new ArrayList<>();
        for (int i=0;i<=list.size();i++){
            listVO.add(
                    MajorDicVO.builder()
                    .majorName(list.get(i).getMajorName())
                    .majorId(list.get(i).getMajorId())
                    .num(i)
                    .build());

        }
        boolean success = ExcelUtils
                .writeExcel(MajorDicVO.class, listVO, "专业代号", response, "五邑大学困难鉴定系统专业代号");
        if (success){
            return Result.success();
        }
        return Result.error();
    }

    @SaIgnore//可以匿名访问该接口
    @GetMapping("/downloadSquadTempleExcel")
    public Result downloadSquadTempleExcel(HttpServletResponse response) throws IOException {
        List<SquadExcelDTO> list=new ArrayList<>();
        boolean success = ExcelUtils
                .writeExcel(SquadExcelDTO.class, list, "模板", response, "五邑大学困难鉴定系统班级录入模板");
        if (success){
            return Result.success();
        }
        return Result.error();
    }

    @SaIgnore//可以匿名访问该接口
    @GetMapping("/importSquadExcel")
    public Result importSquadExcel(@RequestPart(value = "file") MultipartFile file) throws IOException {
        JobThreadConfig jobThreadConfig=new JobThreadConfig();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        //设置执行异步的线程工作
        jobThreadConfig.setJob(() -> {
            SquadListener squadListener=new SquadListener(squadDicRepository);
            try {
                EasyExcel.read(file.getInputStream(), SquadExcelDTO.class, squadListener);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        //异步执行任务
        ConcurrentJobThreadUtils.doJob(jobThreadConfig,executorService);
        return Result.success();
    }

}
